import Taro, { Component } from '@tarojs/taro'
import { View, Text, Image } from '@tarojs/components'
import { AtList, AtListItem, AtButton, AtActionSheet } from 'taro-ui'
import { DNavBar, DAtInpute, Ddialog } from '@/components'
import classNames from 'classnames'
import './logisticsinfodetail.scss'
import http from '@/api'
import common from '@/common'
import sdk from '@/common/sdk'
const itembg = require('../assets/positioning.png')
const header = require('../assets/header.png')
const right = require('../assets/right.png')
//底部图标
const icon_chat = require('../assets/icon_chat.png')
const icon_phone = require('../assets/icon_phone.png')
export default class LogisticsinfodetailBox extends Component {

    constructor(props) {
        super(props)
        this.state = {
            accContent: '企业账户未开通电子收款账户，将会影响企业收款，是否前往开通？',
            type: '',
            logisticsinfo: { cdCarModels: [] },
            carform: {},
            list: [],
            seletOne: {
                defNoop: () => {
                    this.state.seletOne.isOpened = false
                    this.setState({
                        seletOne: { ...this.state.seletOne },
                    })
                }
            }, // 单选对象
            statusHtml: false,
            self: '',
            title: '物流信息详情',
            showAccDialog: false,
            imIdStatus: ''
        }
    }
    componentWillMount() {
        sessionStorage.removeItem('selectCar')
        let { id, type } = this.$router.params
        this.setState({ type, title: !type ? '物流信息详情' : '我的物流详情' })
        this.gettransDetail(id)
    }


    initSelectOne = ({ title }) => {
        return new Promise((res, rej) => {
            this.setState({
                seletOne: {
                    ...this.state.seletOne,
                    isOpened: true,
                    title,
                    commit: () => this.addQuote()
                    // sList: sList.filter(item => (item.status = this.state.carform[bind] === item.text, true)), // 反显高亮值
                    // selectListItem: (item) => {
                    //   item.status = !item.status
                    //   if (item.status) {
                    //     this.state.seletOne.value = item
                    //     res.call(this, item)
                    //   }
                    //   this.state.seletOne.isOpened = false
                    //   this.setState({
                    //     seletOne: { ...this.state.seletOne },
                    //   })
                    // }
                }
            })
        })
    }

    gettransDetail(id) {
        http.getDetailTrans({ id }).then(res => {
            if (!JSON.stringify(res)) {
                return
            }
            res.cdCarModels = res.cdCarModel.split('#')
            let { type } = this.state
            let creatorId = ''
            if (localStorage.getItem('userInformation')) {
                let { dsfUserEntity = '' } = JSON.parse(localStorage.getItem('userInformation'))
                creatorId = dsfUserEntity.userId
            }
            let self = res.creatorId === creatorId ? '1' : '0'
            if (res.isQuotedPrice === '1') {
                type = ''
            } else if (res.isQuotedPrice === '0' && self === '1') {
                type = 'logisticsinfodetail'
            }
            this.setState({
                logisticsinfo: res,
                statusHtml: true,
                list: res.quotedList.filter(item => item),
                type,
                self
            })
            // console.log(res)
        })
    }

    onClickHandle(item) {
        if (item.tqPrice === '***') {
            return Taro.showToast({
                icon: 'none',
                title: '对方报价已隐藏！'
            })
        }
        let { self } = this.state
        if (!item.id) {
            return Taro.showToast({
                icon: 'none',
                title: '当前数据异常！'
            })
        }
        Taro.redirectTo({
            url: `/pages/quotedetail/quotedetail?id=${item.id}&self=${self}`
        })
    }

    addQuote() {
        const { logisticsinfo, carform } = this.state
        const carInfo = JSON.parse(sessionStorage.getItem('selectCar'))
        if (!carform.carGuiPrice) {
            Taro.showToast({
                title: '请填写报价价格',
                icon: "none",
                duration: 800
            })
            return
        }
        if (!carInfo || !carInfo.id) {
            Taro.showToast({
                title: '请选择承运车辆',
                icon: "none",
                duration: 800
            })
            return
        }
        let obj = {
            "refCdId": logisticsinfo.id,
            "refCdNo": logisticsinfo.cdNo,
            "refCiId": carInfo.id,
            "refCiName": carInfo.title,
            "tqPrice": carform.carGuiPrice,
            "tqRemark": carform.carRemark,
        }
        http.addQuote(obj).then(res => {
            this.setState({ carform: {}, seletOne: {} })
            this.componentWillMount()
            Taro.showToast({
                title: '提交成功',
                duration: 800
            })
        })
    }
    //新增报价
    async handlequote() {
        // infoByEnterprise 这个接口如果返回空对象则说明是第一次进行过电子登记簿的开通，需要引导用户开通电子登记簿
        let accountInfo = await http.infoByEnterprise()
        const userInfo = await http.myselfDetail()
        let keys = Object.keys(accountInfo)

        if (!keys.length) {
            // 企业员工
            if (userInfo.imIdStatus == 2) {
                this.setState({
                    accContent: '本企业尚未开通企业收款账户，请联系企业管理员开通后再操作。',
                    imIdStatus: userInfo.imIdStatus
                })
            }
            this.setState({
                showAccDialog: true
            })
        } else {
            // 已经进行过开通
            if (accountInfo.status == '1') {
                // 电子登记簿开通审核中
                Taro.showToast({
                    title: '电子登记簿开通申请正在审核中，请耐心等待。',
                    icon: 'none'
                })
            } else if (accountInfo.status == '2') {
                // 审核被拒
                this.setState({
                    accContent: '电子登记簿开通申请被拒绝，是否重新开通？'
                })
            } else {
                // 审核通过
                this.initSelectOne({ title: '报价' })
            }
        }
    }

    // 下架物流
    httpLeaveTrans(id) {
        http.leaveTrans({ id }).then(res => {
            Taro.showToast({
                title: '下架成功',
                mask: true,
                duration: 800
            }).then(res => {
                setTimeout(() => {
                    Taro.redirectTo({
                        url: `/pages/mylogistics/mylogistics?active=1`
                    })
                }, 1000);
            })

        })
    }
    //删除物流
    delTrans(id) {
        http.delTrans({ id }).then(res => {
            Taro.showToast({
                title: '删除成功',
                mask: true,
                duration: 800
            }).then(res => {
                setTimeout(() => {
                    Taro.navigateTo({
                        url: `/pages/mylogistics/mylogistics`
                    })
                }, 1000);
            })

        })
    }
    handleResubmit(type) {
        // console.log(type)
        if (type === 1) {
            this.httpLeaveTrans(this.$router.params.id)
        } else if (type === 2) {
            this.delTrans(this.$router.params.id)
        }
    }
    selectCarInfo = carInfo => {
        const { logisticsinfo } = this.state
        // alert(logisticsinfo.entId)
        if (logisticsinfo.cdShowStatus === '1') {
            Taro.showToast({
                title: "买家已隐藏联系方式，请直接报价，等待买家主动联系",
                icon: 'none'
            })
            // alert('')
        } else {
            Taro.navigateTo({
                url: `/pages/companydetail/companydetail?id=${logisticsinfo.entId}`
            })
        }

    }

    selectCarPop = () => {
        Taro.navigateTo({
            url: `/pages/transportmgr/transportmgr?type=selectCar`
        })
    }

    getSelectCarPop() {
        const carInfo = JSON.parse(sessionStorage.getItem('selectCar'))
        if (carInfo) {
            this.setState({ carform: Object.assign(this.state.carform, { carDesc: carInfo.title + ' ' + carInfo.order }) })
            this.initSelectOne({ title: '报价' })
        }
    }

    componentDidShow() {
        this.getSelectCarPop()
        sdk.setTitleInfo(this.state.title)
    }

    bindCarform(val, e, prop) {
        if (prop.bind) {
            if (prop.bind === 'carGuiPrice') {
                let Digit = common.getDigit(val, this.state.carform.carGuiPrice)
                this.setState({
                    carform: Object.assign(this.state.carform, { [prop.bind]: Digit }),
                })
            } else {
                this.setState({
                    carform: Object.assign(this.state.carform, { [prop.bind]: val }),
                })
            }

        }
    }
    bindMapAddress(address = '', type) {
        Taro.navigateTo({
            url: '/pages/selectmap/selectmap?type=' + type + '&address=' + address,
        })
    }
    onInfoHandle() {
        if (window.bridge) {
            const { logisticsinfo } = this.state
            // window.bridge.callHandler('IMChat', { 'tephone': logisticsinfo.creatorContact }, function responseCallback(res) { })
            let name = logisticsinfo.cdStartTime + '/' + (logisticsinfo.cdStart || logisticsinfo.cdStartDetail) + '/' + (logisticsinfo.cdEnd || logisticsinfo.cdEndDetail)
            sdk.setWechatInfo(logisticsinfo.creatorContact, 3, name)
        }
    }

    onTelphone() {
        if (window.bridge) {
            let { logisticsinfo } = this.state
            window.bridge.callHandler('call', { 'tephone': logisticsinfo.creatorContact }, function responseCallback(res) { })
        }
    }

    onCancel() {
        this.setState({
            showAccDialog: false
        })
    }
    onSure() {
        this.onCancel()
        if (this.state.imIdStatus != 2) {
            Taro.navigateTo({
                url: `/pages/accountBook/accountBook`
            })
        }
    }

    render() {
        const {
            list,
            type,
            logisticsinfo,
            seletOne,
            carform,
            title,
            showAccDialog,
            accContent,
            imIdStatus
        } = this.state
        const _btnName = localStorage.getItem('_btnName') || '下架'
        return (
            <View className='b_logisticsinfodetail'>
                <DNavBar title={title}></DNavBar>
                <View className='b_logisticsinfodetail__box'>
                    <View className="b_logisticsinfodetail__info">
                        <View className="item_title">
                            <Text className="item_title__left">物流信息编号</Text>
                            <Text className="item_title__right">{logisticsinfo.cdNo}</Text>
                        </View>
                        <View className="item_title">
                            <Text className="item_title__left">始发地址</Text>
                            <View className="item_title__right">{logisticsinfo.cdStart || logisticsinfo.cdStartDetail}</View>
                            <Image onClick={this.bindMapAddress.bind(this, logisticsinfo.cdStart || logisticsinfo.cdStartDetail, 1)} src={itembg} className='item_title__icon'></Image>
                        </View>
                        <View className="item_title">
                            <Text className="item_title__left">目的地址</Text>
                            <View className="item_title__right">{logisticsinfo.cdEnd || logisticsinfo.cdEndDetail}</View>
                            <Image onClick={this.bindMapAddress.bind(this, logisticsinfo.cdEnd || logisticsinfo.cdEndDetail, 2)} src={itembg} className='item_title__icon'></Image>
                        </View>
                        <View className="item_title">
                            <Text className="item_title__left">发车日期</Text>
                            <Text className="item_title__right">{logisticsinfo.cdStartTime}</Text>
                        </View>
                    </View>
                    <View className="b_logisticsinfodetail__info">
                        <View className="item_title">
                            <Text className="item_title__left">车辆1型号</Text>
                            <Text className="item_title__right">{logisticsinfo.cdCarModels[0]}</Text>
                        </View>
                        {
                            logisticsinfo.cdCarModels[1] && <View className="item_title">
                                <Text className="item_title__left">车辆2型号</Text>
                                <Text className="item_title__right">{logisticsinfo.cdCarModels[1]}</Text>
                            </View>
                        }
                    </View>
                    <View className="b_logisticsinfodetail__info">
                        <View className="item_title">
                            <Text className="item_title__left">备注</Text>
                            <Text className="item_title__right">{logisticsinfo.cdComment || '（空）'}</Text>
                        </View>
                    </View>
                    {
                        !type && <View className="b_logisticsinfodetail__carinfo" onClick={this.selectCarInfo}>
                            <View className="item_title">
                                <View className='item_title__left'>
                                    <View className='item_title__left_box'>
                                        <Image src={logisticsinfo.entPhoto || header} className="item_title__left_image"></Image>
                                    </View>

                                </View>
                                <View className='item_title__center'>
                                    <Text className='item_title__center_company'>{logisticsinfo.entName}</Text>
                                    <View className='item_title__center_position'>
                                        <Text className='item_title__center_padding'>{logisticsinfo.entDis}</Text>
                                        <Text className='item_title__center_padding'></Text>
                                    </View>
                                    <View className='item_title__center_phone'>
                                        <Text className='item_title__center_padding'>联系方式：</Text>
                                        <Text className='item_title__center_padding'>{logisticsinfo.creator || '--'}</Text>
                                        <Text className='item_title__center_padding'> {!+logisticsinfo.cdShowStatus ? logisticsinfo.creatorContact : '***********'}</Text>
                                    </View>
                                </View>
                                <View className='item_title__right'>
                                    <Image src={right} className="item_title__right_icon"></Image>
                                </View>
                            </View>
                        </View>
                    }

                    <View className='b_logisticsinfodetail__atlist'>
                        <View className='b_logisticsinfodetail__atlist_title'>已经有{logisticsinfo.viewedTime}位商家查看、共有{list.length || 0}个报价</View>
                        <AtList>
                            {
                                list && list.map((item, i) => {
                                    return <AtListItem key={i} arrow='right' title={item.entName} extraText={item.tqPrice + '元'} onClick={this.onClickHandle.bind(this, item)}></AtListItem>
                                })
                            }
                        </AtList>
                    </View>
                </View>
                <View>
                    <AtActionSheet className="at-select-one" isOpened={seletOne.isOpened} onClose={seletOne.onClose || seletOne.defNoop}>
                        <View className='at-select-one__title'>
                            <View className='at-select-one__title_cancel' onClick={seletOne.cancel || seletOne.defNoop}>{seletOne.cancelText || '取消'}</View>
                            <View className='at-select-one__title_item'>{seletOne.title}</View>
                            <View className='at-select-one__title_submit' onClick={seletOne.commit || seletOne.defNoop}>{seletOne.commitText || '提交'}</View>
                        </View>
                        <View className='b_logisticsinfodetail__sheet__content'>
                            <DAtInpute value={carform.carGuiPrice} bind='carGuiPrice' require={true} type="number" onChange={this.bindCarform.bind(this)} title='报价价格'>元</DAtInpute>
                            <DAtInpute value={carform.carDesc} bind='carDesc' require={true} onChange={this.bindCarform.bind(this)} title='承运车辆' icon='chevron-right' placeholder='请选择承运车辆' onRightHanlde={this.selectCarPop}></DAtInpute>
                            <DAtInpute value={carform.carRemark} bind='carRemark' maxLength={500} onChange={this.bindCarform.bind(this)} title='备注' placeholder='可给委托方留言'></DAtInpute>
                        </View>
                    </AtActionSheet>
                </View>
                {
                    !type ?
                        !+logisticsinfo.cdShowStatus ?
                            <View className='b_logisticsinfodetail__footer'>
                                <View className='b_logisticsinfodetail__footer_left'>
                                    {
                                      false && <View className='b_logisticsinfodetail__footer_item' onClick={this.onInfoHandle.bind(this)}>
                                        <Image src={icon_chat} className='b_logisticsinfodetail__footer_item_image'></Image>
                                        <Text>私信</Text>
                                    </View>
                                    }
                                    <View className='b_logisticsinfodetail__footer_item' onClick={this.onTelphone.bind(this)}>
                                        <Image src={icon_phone} className='b_logisticsinfodetail__footer_item_image'></Image>
                                        <Text>电话</Text>
                                    </View>
                                    {/* <View className='b_logisticsinfodetail__footer_item'></View> */}
                                </View>
                                <View className='b_logisticsinfodetail__footer_right' onClick={this.handlequote.bind(this)}>
                                    <Text>立即报价</Text>
                                </View>
                            </View>
                            :
                            <View className='b_logisticsinfodetail__btn'>
                                <AtButton className='item_btn' onClick={this.handlequote.bind(this)}>立即报价</AtButton>
                            </View>
                        :
                        <View className='b_logisticsinfodetail__btn'>
                            <AtButton className={classNames('item_btn', _btnName === '删除' ? 'item_btn__default' : '')} onClick={this.handleResubmit.bind(this, _btnName === '删除' ? 2 : 1)}>{_btnName}物流</AtButton>
                        </View>
                }

                <Ddialog isShow={showAccDialog} content={accContent} btnText={imIdStatus == 2 ? '我知道了' : '前往开通'} onCancel={this.onCancel.bind(this)} onSure={this.onSure.bind(this)}></Ddialog>
            </View>
        )
    }
}
